using System;
using System.IO;

namespace MySqlBackUp.Server.Core
{

    public class JsonHelper<T>
    {
        public string GetJson(T t)
        {
            return Newtonsoft.Json.JsonConvert.SerializeObject(t);
        }

        public T ParseJson(string json)
        {
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json);
        }

        public void SaveData(string fileName, T t)
        {
            var json = GetJson(t);
            var currPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "json");
            fileName = Path.GetFileNameWithoutExtension(fileName);
            FilesHelper.CreateNewFile(Path.Combine(currPath, fileName + ".json"), json);
        }

        public T GetData(string fileName)
        {
            var currPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "json");
            fileName = Path.GetFileNameWithoutExtension(fileName);
            var json = File.ReadAllText(Path.Combine(currPath, fileName + ".json"));
            return ParseJson(json);
        }

        public void SaveJsonData(string fileName, string json)
        {
            var currPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "json");
            fileName = Path.GetFileNameWithoutExtension(fileName);
            FilesHelper.CreateNewFile(Path.Combine(currPath, fileName + ".json"), json);
        }

        public string GetJsonData(string fileName)
        {
            var currPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "json");
            fileName = Path.GetFileNameWithoutExtension(fileName);
            var json = File.ReadAllText(Path.Combine(currPath, fileName + ".json"));
            return json;
        }
    }
}